<template>
  <div class="InfoBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="text" icon="el-icon-back" style="margin-right:15px;" @click="$router.go(-1)">返回</el-button>
        <span>修改文章</span>
      </div>
      <div v-loading="loading"
        v-show="loading"
        element-loading-text="正在加载文章"
        element-loading-spinner="el-icon-loading" class="loading"></div>
      <el-form
        v-show="!loading"
        :rules="rules"
        ref="ruleForm"
        :model="info"
        class="formbox"
        label-width="80px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input ref="title" v-model="info.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="文章类别" prop="sortId">
          <el-select
            v-model="info.sortId"
            placeholder="请选择文章类型"
            style="width: 100%"
          >
            <el-option
              v-for="item of typeList"
              :label="item.type_name"
              :key="item.type_id"
              :value="item.type_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <FullEditor ref="fullEditor"></FullEditor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <div class="cropper">
            <vueCropper
              class="vueCropper"
              @mouseenter.native="enter"
              @mouseleave.native="leave"
              ref="cropper"
              :img="option.img"
              :outputSize="option.outputSize"
              :outputType="option.outputType"
              :info="option.info"
              :full="option.full"
              :fixed="true"
              :fixedNumber="[4, 3]"
              :autoCrop="true"
              :canMove="true"
              :autoCropWidth="400"
              :autoCropHeight="300"
            ></vueCropper>
            <div class="previewBox">
              <img :src="previewUrl" ref="coverImg" alt="" />
              <label for="finp" class="btnbox">
                <el-button type="primary">选择封面</el-button>
                <input
                  type="file"
                  ref="ok"
                  @change="init"
                  value="选择封面"
                  id="finp"
                  name="finp"
                />
              </label>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-s-promotion" @click="handleSubmit(0)"
            >发布</el-button
          >
          <el-button type="info" icon="el-icon-s-management" @click="handleSubmit(1)"
            >存草稿</el-button
          >
        </el-form-item>
      </el-form>
      <el-backtop target=".el-card" :bottom="100"></el-backtop>
    </el-card>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import FullEditor from '../../components/fullEditor'
import { articleTypeApi } from '../../apis/articleType'
import { articleApi } from '../../apis/article'
const articleType = articleTypeApi()
const article = articleApi()
export default {
  name: 'articlePublish',
  components: {
    FullEditor,
    VueCropper
  },
  data () {
    return {
      info: {
        id: 0,
        title: '',
        sortId: '',
        content: '',
        cover_img: '',
        status: 1,
        create_time: '',
        update_time: ''
      },
      loading: true,
      fileList: [],
      previewUrl: '',
      option: {
        img: '',
        outputSize: 1,
        outputType: 'png',
        fixed: true,
        info: true,
        full: false
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        sortId: [{ required: true, message: '请输入文章类别', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'change' }],
        cover_img: [{ required: true, message: '请输入文章封面', trigger: 'change' }]
      },
      typeList: []
    }
  },
  methods: {
    // 初始化获取文章分类信息
    getArticleType () {
      articleType.getAllArticleType().then((res) => {
        if (res && res.code === 200) {
          this.typeList = res.data
        }
      })
    },
    ToBase64 (url) {
      return new Promise((resolve, reject) => {
        const image = new Image()
        image.src = url
        image.onload = () => {
          const canvas = document.createElement('canvas')
          canvas.width = image.naturalWidth // 使用 naturalWidth 为了保证图片的清晰度
          canvas.height = image.naturalHeight
          canvas.style.width = `${canvas.width / window.devicePixelRatio}px`
          canvas.style.height = `${canvas.height / window.devicePixelRatio}px`
          const ctx = canvas.getContext('2d')
          if (!ctx) {
            return null
          }
          ctx.drawImage(image, 0, 0)
          const base64 = canvas.toDataURL('image/png')
          return resolve(base64)
        }
        image.onerror = (err) => {
          return reject(err)
        }
      })
    },
    BloBToBase64 (blob, callback) {
      const reader = new FileReader()
      reader.onload = function (e) {
        callback(e.target.result)
      }
      reader.readAsDataURL(blob)
    },
    // 获得富文本内容
    getContent () {
      this.info.content = this.$refs.fullEditor.content
    },
    // 截图的两个操作
    enter () {
      if (this.option.img === '') {
        return
      }
      this.$refs.cropper.startCrop()
    },
    leave () {
      this.$refs.cropper.stopCrop()
      this.view()
    },
    // 获取截图的base64值
    view () {
      this.$refs.cropper.getCropData((data) => {
        this.info.cover_img = data
      })
    },
    // 文件选择
    init () {
      const file = this.$refs.ok.files[0]
      if (file.type && (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg')) {
        this.BloBToBase64(file, (e) => {
          this.previewUrl = e
          this.option.img = e
        })
      } else {
        this.$message({
          message: '仅限选择jpg、jpeg、png格式图片',
          type: 'warning'
        })
      }
    },
    formatTime (date) {
      const Y = date.getFullYear().toString()
      const M = (date.getMonth() + 1).toString()
      const D = date.getDate().toString()
      const h = date.getHours().toString()
      const m = date.getMinutes().toString()
      const s = date.getSeconds().toString()
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
    },
    handleSubmit (type) {
      this.view()
      const date = new Date()
      this.info.update_time = this.formatTime(date)
      if (type === 1) {
        this.info.status = 1
      } else {
        this.info.status = 0
      }
      this.getContent()
      article.updateArticle(this.info).then((res) => {
        if (res && res.code === 200) {
          if (!this.info.status) {
            this.$message({
              message: '文章已发表！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '文章已存至草稿箱！',
              type: 'success'
            })
          }
          this.$router.push('/articleList')
        }
      })
    },
    getArticleById (id) {
      article.getArticleById({ id: id }).then(res => {
        if (!res && res.code !== 200) {
          return
        }
        this.previewUrl = res.data[0].cover_img
        this.option.img = res.data[0].cover_img
        Object.keys(this.info).forEach((key) => (this.info[key] = res.data[0][key]))
        this.info.sortId = res.data[0].sort_id
        this.info.id = res.data[0].article_id
        this.$refs.fullEditor.content = res.data[0].content
        this.loading = false
      })
    }
  },
  mounted () {
    this.getArticleType()
    if (this.$route.query.id) {
      this.getArticleById(this.$route.query.id)
    }
  }
}
</script>

<style lang="less" scoped>
.cropper {
  width: 650px;
  height: 300px;
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  .vueCropper {
    margin-right: 20px;
    width: 400px;
  }
}
.previewBox {
  display: flex;
  flex-direction: column;
  img {
    width: 200px;
    margin-bottom: 15px;
  }
  .btnbox {
    position: relative;
    input {
      opacity: 0;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
}
.loading{
  margin-top:10%;
}
.InfoBox {
  padding: 10px;
  height: 100%;
}
.box-card {
  width: 100%;
  height: 100%;
  overflow: scroll;
}
</style>
